package com.sagereal.wtc.factorymode.Activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.sagereal.wtc.factorymode.R;

import java.io.IOException;


public class CameraActivity extends BaseActivity {
    private Button mTestPass,mTestFail,mChangeBtn;
    private SurfaceView mSufaceView;
    private SurfaceHolder mSufaceHolder;
    private Camera mCmera;
    private int mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK; // 默认后置摄像头
    private boolean mSureBtn = false;
    private int mI = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        setTitle(getString(R.string.title_camera_test));

        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mChangeBtn = findViewById(R.id.change_btn);
        mSufaceView = findViewById(R.id.surface_view);
        mSufaceHolder = mSufaceView.getHolder();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED){
            showPermissionDialog();
        }

        mSufaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                openCamera(mCurrentCameraId);
            }
            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mSufaceHolder.getSurface() == null) {
                    return;
                }
                try {
                    mCmera.stopPreview();
                } catch (Exception e) {
                    return;
                }
                setCameraDisplayOrientation();
                try {
                    mCmera.setPreviewDisplay(mSufaceHolder);
                    mCmera.startPreview();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                releaseCamera();
            }
        });
        if (savedInstanceState != null) {
            mCurrentCameraId = savedInstanceState.getInt("currentCameraId", Camera.CameraInfo.CAMERA_FACING_BACK);
            mSureBtn = savedInstanceState.getBoolean("changebtn", false);
        }
        initView();
    }
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentCameraId", mCurrentCameraId);
        outState.putBoolean("changebtn", mSureBtn);
    }

    /*提示权限需要申请*/
    private void showPermissionDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.permission_ask)
                .setMessage(R.string.permission_content)
                .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                })
                .setPositiveButton(getString(R.string.go_set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                })
                .setCancelable(false)
                .show();
    }

    private void initView() {
        mChangeBtn.setOnClickListener(v -> {
            applySavedLanguage();
            if (mCurrentCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
                mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_FRONT;
            } else {
                mCurrentCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
            }
            mSureBtn = true;
            releaseCamera();
            openCamera(mCurrentCameraId);
            mChangeBtn.setEnabled(false);
            new Thread(() -> {
                try {
                    Thread.sleep(1000); // 等待Toast显示时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                runOnUiThread(() -> mChangeBtn.setEnabled(true));
            }).start();
        });
        // 测试通过
        mTestPass.setOnClickListener(v -> {
            if(mSureBtn){
                Intent intent = new Intent(CameraActivity.this, ItemTestActivity.class);
                intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
                intent.putExtra("status", "pass");
                intent.putExtra("check", getIntent().getStringExtra("check"));
                setResult(RESULT_OK , intent);
                finish();
            }else {
                mTestPass.setEnabled(false);
                Toast.makeText(this, getString(R.string.camera_passbtn_notify), Toast.LENGTH_SHORT).show();
                new Thread(() -> {
                    try {
                        Thread.sleep(3000); // 等待Toast显示时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runOnUiThread(() -> mTestPass.setEnabled(true));
                }).start();
            }
        });

        // 测试失败
        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(CameraActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1));
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
    }
    private void openCamera(int cameraId) {
        try {
            mCmera = Camera.open(cameraId);
            mCmera.setPreviewDisplay(mSufaceHolder);
            setCameraDisplayOrientation();
            mCmera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setCameraDisplayOrientation() {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(mCurrentCameraId, info);
        int rotation = getWindowManager().getDefaultDisplay().getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0: degrees = 0; break;
            case Surface.ROTATION_90: degrees = 90; break;
            case Surface.ROTATION_180: degrees = 180; break;
            case Surface.ROTATION_270: degrees = 270; break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        mCmera.setDisplayOrientation(result);
    }

    private void releaseCamera() {
        if (mCmera != null) {
            mCmera.stopPreview();
            mCmera.release();
            mCmera = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mI++;
        if(mI > 1){
            Log.d("wentianci", "onResume: "+ mI);
            // 在 onResume 中再次检查相机权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                // 如果没有权限，则直接结束活动
                finish();
            }
        }
    }

}
